import axios from 'axios'
import { FailFN } from '@/DceMessage'
// import { createWsse } from '@/utils/dictStandard.js'
import router from '@/router'
// import { Item } from 'ant-design-vue/lib/menu'

// access_token，查询携带，有效期2h
// refresh_token，刷新携带，有效期7d
var userToken = window.localStorage.getItem('attendance-records') ?
    JSON.parse(window.localStorage.getItem('attendance-records')).token :
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjE2MDcxODczMDE4MzY3ODc3MTIsIlJhbmRvbSI6IjZkSE0xIiwiZXhwIjoxNzM1Mzk2Njk0LCJpc3MiOiJkZml0YyJ9.xvQcS0LthUEEOADqd7eqdxF-adVnk6yFdNBnFFRgo9E'

// 设置请求头
const _axios = axios.create({
        // baseURL: '/api/', // 开发环境
        baseURL: '/attendance/', // 正式环境
        // baseURL: 'http://47.95.27.66/',
        // baseURL: 'https://fipdev.dfitc.com.cn/attendance/',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Authorization: 'WSSE profile="UsernameToken"',
            'X-WSSE': 'Username="fd930bd9bfe94a89949f1305f989096a", PasswordDigest="b6aa922b1dd6ef4946072632efdc09f0bda28d8075e9d4f286ae896459d8b126", Nonce="2249a8d6-3e5f-4bfe-a7c9-3bf2a746926d", Created="2022-11-25T10:43:40Z"',
            'X-TOKEN': userToken,
            // 表示跨域请求时是否需要使用凭证,允许跨域携带cookie信息
            withCredentials: false,
            // 允许跨域
            'Access-Control-Allow-Origin-Type': '*'
        },
        timeout: 10 * 1000
    })
    // 请求拦截器
_axios.interceptors.request.use(
        config => {
            var userToken = window.localStorage.getItem('attendance-records') ?
                JSON.parse(window.localStorage.getItem('attendance-records')).token :
                'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOjE2MDcxODczMDE4MzY3ODc3MTIsIlJhbmRvbSI6IjZkSE0xIiwiZXhwIjoxNzM1Mzk2Njk0LCJpc3MiOiJkZml0YyJ9.xvQcS0LthUEEOADqd7eqdxF-adVnk6yFdNBnFFRgo9E'

            config.headers['X-TOKEN'] = userToken

            return config
        },
        error => {
            return Promise.reject(error)
        }
    )
    // 响应拦截器
_axios.interceptors.response.use(
    response => {
        console.log('ddd', response)
        switch (response.data.Status) {
            case 'success':
                return response
            case 'fail':
                FailFN(response.data.Message)
                if (response.data.Message == '无权限') {
                    localStorage.removeItem('attendance-records')
                    router.push('/login')
                }
                break
            default:
                message.error(response.data.Message)
                break
        }
    },
    // validateStatus: function (status) {
    //   return status >= 200 && status < 300; // default
    // },
    error => {
        // message.error(`网络错误，错误提示为：${error.message}!`)
    }
)

export default {
    post(url, data, config) {
        return _axios({
            method: 'post',
            url,
            data: data,
            ...config
        })
    },

    put(url, data, config) {
        return _axios({
            method: 'put',
            url,
            data: data,
            ...config
        })
    },

    get(url, data, config) {
        return _axios({
            method: 'get',
            url,
            params: data,
            ...config
        })
    },

    delete(url) {
        return _axios({
            method: 'delete',
            url
        })
    },
    /**
     * 请求form-data方法,上传文件使用
     */
    postFormData(url, params) {
        return _axios.post(url, params, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
    }
}

export { _axios }

export function getNewToken() {
    _axios
        .get('/refresh', {
            // baseURL: '/api'
        })
        .then(res => {
            if (res) {
                localStorage.setItem('access_token', res.object.access_token)
                localStorage.setItem('refresh_token', res.object.refresh_token)
                localStorage.setItem('visitTime', Date.parse(new Date())) // 将本次请求的时间放入缓存
            }
        })
}
export function refreshToken() {
    const nowDate = Date.parse(new Date()) // 定义当前时间
    const visitTime = Number(localStorage.getItem('visitTime')) // 获取旧时间
    const refresh_token = localStorage.getItem('refresh_token') // 获取长token
    if (visitTime) {
        const timeDiff = nowDate - visitTime
        console.log(`时间相差 >>>>>>>${timeDiff}毫秒`)
            // 如果间隔时间大于1个小时
        if (timeDiff > 1000 * 60 * 60) {
            if (refresh_token) {
                getNewToken() // 调用刷新token接口
            }
        }
    }
}